package com.newear.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.ArrayMap;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.newear.MyApplication;
import com.newear.R;
import com.newear.bean.CustomerInfo;
import com.newear.constant.DataType;
import com.newear.constant.RequireParams;
import com.newear.happyDialog.CamaraCheckDialog;
import com.newear.message.MessageDispatcher;
import com.newear.message.MessageType;
import com.newear.util.HardWare;
import com.newear.util.MyLogger;
import com.newear.util.MyMediaPlayer;
import com.newear.util.ProgressDialogUtil;
import com.newear.util.T;
import com.newear.util.Validator;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class HappyPersonDetailSelectActivity extends AppCompatActivity {
    private static final String TAG = "HappyPersonDetailSelect";
    private Context mContext;
    private CamaraCheckDialog mCamaraCheckDialog;
    private EditText et_person_num;//会员编号
    private LinearLayout lL_person_age_container;
    private LinearLayout lL_person_sex_container;
    private LinearLayout lL_person_statu_container;
    private ImageView img_person_close;
    private Button btn_page_next;
    private ArrayList mAgeList;//年龄数组
    private ArrayList mSexList;//性别数组
    private ArrayList mStatuList;//状态数组
    private List<Button> ageButtons;
    private List<Button> sexButtons;
    private List<Button> statuButtons;
    private MediaPlayer mediaPlayer;
    private String key;
    private MyHandler myHandler;
    private ProgressDialog mProgressDialog; //网络请求时用的进度条

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_happy_person_detail_select);
        init();
        findViews();
        setListeners();
        addAgeButtonViews();
        addSexButtonViews();
        addStatuButtonViews();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        HardWare.registerActivity(this);
    }

    private void init(){
        mContext = this;
        this.key = this.hashCode() + "";
        myHandler = new MyHandler(this);
        mProgressDialog = ProgressDialogUtil.getProgressDialog(mContext);
        HardWare.registerActivity(this);
        mediaPlayer = MyMediaPlayer.getInstance().playing(this, "raw/ask.mp3");
        mAgeList = new ArrayList();
        mAgeList.add("1-12岁");
        mAgeList.add("13-18岁");
        mAgeList.add("19-25岁");
        mAgeList.add("26-35岁");
        mAgeList.add("36-45岁");
        mAgeList.add("46-60岁");
        mAgeList.add("60岁以上");

        mSexList = new ArrayList();
        mSexList.add("男");
        mSexList.add("女");

        mStatuList = new ArrayList();
        mStatuList.add("孕期");
        mStatuList.add("哺乳");
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.release();
        }
        mediaPlayer = null;
    }

    private void findViews(){
        et_person_num = (EditText) findViewById(R.id.et_person_num);
        lL_person_age_container = (LinearLayout) findViewById(R.id.lL_person_age_container);
        lL_person_sex_container = (LinearLayout) findViewById(R.id.lL_person_sex_container);
        lL_person_statu_container = (LinearLayout) findViewById(R.id.lL_person_statu_container);
        img_person_close = (ImageView) findViewById(R.id.img_person_close);
        btn_page_next = (Button) findViewById(R.id.btn_page_next);
    }

    private void setListeners(){
        img_person_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        btn_page_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String vipStr = et_person_num.getText().toString().trim();
                if (!Validator.isEffective(vipStr)) {
                    final CamaraCheckDialog camaraCheckDialog = new CamaraCheckDialog(mContext, R.style.dialog, "请先输入会员编号", "再进入下一页", -1);
                    camaraCheckDialog.show();
                    return;
                } else {
                    try {
                        MyApplication.sCustomerInfo.vipNum = Integer.parseInt(vipStr);
                        checkVip(vipStr);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
        });
    }

    /**
     * 检查vip
     */
    private void checkVip(String vipNum) {
        ArrayMap<String, Object> param = new ArrayMap<String, Object>();
        param.put(RequireParams.DATA_TYPE, DataType.CHECK_VIP);
        param.put(RequireParams.MAP_KEY, this.key + DataType.CHECK_VIP);
        param.put(RequireParams.ID, vipNum);
        param.put(RequireParams.CALL_BACK_HANDLER, myHandler);
        MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_DATA, param);
    }

    /**
     * 检查必选项
     */
    private void checkNeedSelected() {
        if (MyApplication.sCustomerInfo.ageGrade == 0) {
            final CamaraCheckDialog camaraCheckDialog = new CamaraCheckDialog(mContext, R.style.dialog, "请先选择年龄", "再进入下一页", -1);
            camaraCheckDialog.show();
            return;
        }
        if (MyApplication.sCustomerInfo.sex == 0) {
            final CamaraCheckDialog camaraCheckDialog = new CamaraCheckDialog(mContext, R.style.dialog, "请先选择性别", "再进入下一页", -1);
            camaraCheckDialog.show();
            return;
        }
        //跳转单选题界面
        Intent intent = new Intent(HappyPersonDetailSelectActivity.this, HappySingleSelectActivity.class);
        startActivity(intent);
    }

    //年龄按钮添加
    private void addAgeButtonViews(){
        if (lL_person_age_container != null) {
            lL_person_age_container.removeAllViews();
        }
        ageButtons = new ArrayList<>();
        for (int i = 0; i < mAgeList.size(); i++) {
            View view = View.inflate(this, R.layout.person_info_custom_btn, null);
            final Button ageBtn = (Button) view.findViewById(R.id.person_info_age_btn);
            if (MyApplication.sCustomerInfo.ageGrade > CustomerInfo.AgeGrade.AGE_UN_SELECTED) {
                if ((i + 1) == MyApplication.sCustomerInfo.ageGrade) {
                    ageBtn.setSelected(true);
                }
            }
            ageButtons.add(ageBtn);
            ageBtn.setText((String)mAgeList.get(i));
            view.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            lL_person_age_container.addView(view);
            final int finalI = i;
            ageBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    for (int j = 0; j < ageButtons.size(); j++) {
                        if (finalI == j) {
                            ageButtons.get(j).setSelected(!ageButtons.get(j).isSelected());
                            if (ageButtons.get(j).isSelected()) {
                                MyApplication.sCustomerInfo.ageGrade = (j + 1);
                                Log.e("josan", "选择了年龄等级：" + MyApplication.sCustomerInfo.ageGrade);
                            } else {
                                MyApplication.sCustomerInfo.ageGrade = CustomerInfo.AgeGrade.AGE_UN_SELECTED;
                                Log.e("josan", "没有选择年龄");
                            }
                        } else {
                            ageButtons.get(j).setSelected(false);
                        }
                    }

                }
            });
        }

    }

    //性别按钮添加
    private void addSexButtonViews(){
        if (lL_person_sex_container != null) {
            lL_person_sex_container.removeAllViews();
        }

        sexButtons = new ArrayList<>();
        for (int i = 0; i < mSexList.size(); i++) {
            View view = View.inflate(this, R.layout.person_sex_custom_btn, null);
            final Button sexBtn = (Button) view.findViewById(R.id.person_info_sex_btn);
            if (MyApplication.sCustomerInfo.sex > CustomerInfo.SexType.UN_SELECTED) {
                if ((i + 1) == MyApplication.sCustomerInfo.sex) {
                    sexBtn.setSelected(true);
                }
            }
            sexBtn.setText((String)mSexList.get(i));
            sexButtons.add(sexBtn);
            view.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            lL_person_sex_container.addView(view);

            final int finalI = i;
            sexBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    for (int j = 0; j < sexButtons.size(); j++) {
                        if (finalI == j) {
                            sexButtons.get(j).setSelected(!sexButtons.get(j).isSelected());
                            if (sexButtons.get(j).isSelected()) {
                                MyApplication.sCustomerInfo.sex = (j + 1);
                                Log.e("josan", "选择了性别等级：" + MyApplication.sCustomerInfo.sex);
                            } else {
                                MyApplication.sCustomerInfo.sex = CustomerInfo.SexType.UN_SELECTED;
                                Log.e("josan", "没有选择性别");
                            }
                        } else {
                            sexButtons.get(j).setSelected(false);
                        }
                    }
                    if (MyApplication.sCustomerInfo.sex == CustomerInfo.SexType.FEMALE) {
                        lL_person_statu_container.setVisibility(View.VISIBLE);
                    } else {
                        lL_person_statu_container.setVisibility(View.GONE);
                        MyApplication.sCustomerInfo.femaleStatu = CustomerInfo.FemaleStatus.UN_SELECTED;
                    }
                }
            });
        }

    }

    //状态按钮添加
    private void addStatuButtonViews(){
        if (lL_person_statu_container != null) {
            lL_person_statu_container.removeAllViews();
        }

        statuButtons = new ArrayList<>();
        for (int i = 0; i < mStatuList.size(); i++) {
            View view = View.inflate(this, R.layout.person_sex_custom_btn, null);
            final Button statuBtn = (Button) view.findViewById(R.id.person_info_sex_btn);
            if (MyApplication.sCustomerInfo.femaleStatu > CustomerInfo.FemaleStatus.UN_SELECTED) {
                if ((i + 1) == MyApplication.sCustomerInfo.femaleStatu) {
                    statuBtn.setSelected(true);
                }
            }
            statuBtn.setText((String)mStatuList.get(i));
            statuButtons.add(statuBtn);
            view.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            lL_person_statu_container.addView(view);

            final int finalI = i;
            statuBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    for (int j = 0; j < statuButtons.size(); j++) {
                        if (finalI == j) {
                            statuButtons.get(j).setSelected(!statuButtons.get(j).isSelected());
                            if (statuButtons.get(j).isSelected()) {
                                MyApplication.sCustomerInfo.femaleStatu = (j + 1);
                                Log.e("josan", "女性的状态：" + MyApplication.sCustomerInfo.femaleStatu);
                            } else {
                                MyApplication.sCustomerInfo.femaleStatu = CustomerInfo.FemaleStatus.UN_SELECTED;
                                Log.e("josan", "没有选择女性状态");
                            }
                        } else {
                            statuButtons.get(j).setSelected(false);
                        }
                    }
                }
            });
        }

    }
    static class MyHandler extends Handler {
        WeakReference<Activity> mActivityReference;

        MyHandler(Activity mActivity) {
            mActivityReference = new WeakReference<Activity>(mActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            try {
                final HappyPersonDetailSelectActivity activity = (HappyPersonDetailSelectActivity) mActivityReference.get();
                if (activity != null) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case MessageType.SHOW_DIALOG:   //显示对话框
                            if (activity.mProgressDialog != null) {
                                activity.mProgressDialog.setMessage("正在检验vip...");
                                activity.mProgressDialog.show();
                            }
                            break;
                        case MessageType.CLOSE_DIALOG:  //关闭对话框
                            if (activity.mProgressDialog != null) {
                                activity.mProgressDialog.dismiss();
                            }
                            break;
                        case MessageType.REQUIRE_DATA_FINISHED: //请求数据完成
                            if (msg.arg1 == DataType.CHECK_VIP) {
                                SparseArray<Object> result = (SparseArray<Object>) msg.obj;
                                String errno = (String) result.get(0);
                                if ("0".equals(errno)) {
                                    boolean status = (boolean) result.get(1);
                                    if (status) {
                                        activity.checkNeedSelected();
                                    } else {
                                        T.shortToast(activity, "会员编号有误，请重新输入！");
                                    }
                                } else if ("1".equals(errno)){
                                    T.shortToast(activity, "请稍后再试...");
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
            } catch (Exception e) {
                MyLogger.e(TAG, "handleMessage Exception!e:" + e.getMessage());
            }
        }
    }

}
